package com.boding.power.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.boding.power.common.Constants;
import com.boding.power.dto.UserDto;
import com.boding.power.model.base.BaseUsers;
import com.boding.power.utils.CryptographyUtil;
import com.boding.power.utils.DataGrid;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Users extends BaseUsers<Users> {
	public static final Users dao = new Users();

	public Users findByUserNameAndPassword(String username, String password) {
		String sql = "select * from users u where u.username = ? and u.password = ? and u.status = 1";
		return dao.findFirst(sql, username,
				CryptographyUtil.md5(password, Constants.SALT));
	}

	public Users findByUsername(String username) {
		if (StringUtils.isNotBlank(username)
				&& StringUtils.isNotEmpty(username)) {
			Users users = dao.findFirst(
					"select * from users u where u.username = ?", username);
			return users;
		}
		return null;
	}

	public DataGrid<UserDto> findByPage(Integer page, Integer rows,
			String searchField, String searchString) {
		Page<Record> records = null;
		if (StringUtils.isNotBlank(searchField)
				&& StringUtils.isNotEmpty(searchField)
				&& StringUtils.isNotBlank(searchString)
				& StringUtils.isNotEmpty(searchString)) {
			records = Db
					.paginate(
							page,
							rows,
							"select u.id,u.username,u.password,u.status,u.create_time,r.description ",
							"from users u,roles r , user_roles ur where u.id = ur.user_id and r.id = ur.id and "
									+ searchField
									+ " = ? order by u.status asc",
							searchString);
		} else {
			records = Db
					.paginate(
							page,rows,
							"select u.id,u.username,u.password,u.status,u.create_time,r.description ",
							"from users u,roles r , user_roles ur where u.id = ur.user_id and r.id = ur.role_id order by u.status desc ,r.id desc");
		}
		
		List<Record> list = records.getList();
		List<UserDto> dtos = new ArrayList<UserDto>();
		for (Record record : list) {
			UserDto dto = new UserDto();
			dto.setId(record.getInt("id"));
			dto.setCreateTime(record.getDate("create_time"));
			dto.setUsername(record.getStr("username"));
			dto.setPassword(record.getStr("password"));
			dto.setDescription(record.getStr("description"));
			dto.setStatus(record.getInt("status"));
			dtos.add(dto);
		}
		DataGrid<UserDto> dataGrid = new DataGrid<UserDto>(records,dtos);
		return dataGrid;
	}
}
